package com.tanhua.manager.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.domain.bo.UserInfoBo;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.Publish;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.*;
import com.itheima.dubbo.api.*;
import com.tanhua.manager.constant.CacheKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/2/18 22:50
 */
@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private FriendApi friendApi;
    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final String MESSAGE = "操作成功";


    /**
     * Mr.Seven的基操
     * @param page
     * @param pagesize
     * @return
     */
    public ResponseEntity findUserList(int page, int pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findList(page, pagesize);

        //PageResult<UserInfo> pageResult = new PageResult<>();
        //pageResult.setPage(page);
        //pageResult.setPagesize(pagesize);
        //pageResult.setPages((int) iPage.getPages());
        //pageResult.setCounts((int) iPage.getTotal());
        //pageResult.setItems(iPage.getRecords());

        List<UserInfoBo> boList = new ArrayList<>();
        for (UserInfo userInfo : iPage.getRecords()) {
            UserInfoBo userInfoBo = new UserInfoBo();
            BeanUtils.copyProperties(userInfo, userInfoBo);
            String userStatus = redisTemplate.opsForValue().get(CacheKey.FREEZE_PREFIX + userInfo.getId());
            if (StringUtils.isBlank(userStatus)) {
                userInfoBo.setUserStatus("1");
            } else {
                userInfoBo.setUserStatus("2");
            }
            boList.add(userInfoBo);
        }

        PageResult<UserInfoBo> boPageResult = new PageResult<>();
        boPageResult.setPage(page);
        boPageResult.setPagesize(pagesize);
        boPageResult.setPages((int) iPage.getPages());
        boPageResult.setCounts((int) iPage.getTotal());
        boPageResult.setItems(boList);

        return ResponseEntity.ok(boPageResult);
    }

    public ResponseEntity findUserInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);

        UserVo vo = new UserVo();
        BeanUtils.copyProperties(userInfo, vo);

        String userStatus = redisTemplate.opsForValue().get(CacheKey.FREEZE_PREFIX + userInfo.getId());
        if (StringUtils.isBlank(userStatus)) {
            vo.setUserStatus("1");
        } else {
            vo.setUserStatus("2");
        }
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findPublishMessages(int page, int pagesize, Long uid, String state) {
        Integer stateInt = null;
        if (StringUtils.isNotBlank(state) && !"''".equals(state) && !"".equals(state)) {
            stateInt = Integer.valueOf(state);
        }

        PageResult<Publish> pageResult = publishApi.findPublishList(page, pagesize, uid, stateInt);

        List<PublishVo> voList = new ArrayList<>();
        for (Publish publish : pageResult.getItems()) {
            PublishVo vo = new PublishVo();

            //查询动态的发布人信息，封装到vo对象
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setTags(userInfo.getTags().split(","));

            //把Publish封装到vo对象
            BeanUtils.copyProperties(publish, vo);
            vo.setId(publish.getId().toHexString());
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
            vo.setDistance("50米");
            vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            voList.add(vo);
        }

        PageResult<PublishVo> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity findPublishById(String publishId) {
        Publish publish = publishApi.findById(publishId);
        //2. 转换成vo
        PublishVo vo = new PublishVo();

        //查询动态的发布人信息，封装到vo对象
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        BeanUtils.copyProperties(userInfo, vo);
        vo.setTags(userInfo.getTags().split(","));

        //把Publish封装到vo对象
        BeanUtils.copyProperties(publish, vo);
        vo.setId(publish.getId().toHexString());
        vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        vo.setDistance("50米");
        vo.setCreateDate(new DateTime(publish.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findCommentList(int page, int pagesize, String messageID) {
        PageResult<Comment> pageResult = commentApi.findComments(page, pagesize, messageID);

        //2. 转换成VO
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : pageResult.getItems()) {
            CommentVo vo = new CommentVo();

            vo.setId(comment.getId().toHexString());
            vo.setContent(comment.getContent());
            vo.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());


            voList.add(vo);
        }

        //3. 构造返回值
        PageResult<CommentVo> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity findVideoList(int page, int pagesize, Long uid) {
        PageResult<Video> pageResult = videoApi.findVideoList(page, pagesize, uid);

        List<VideoVo> voList = new ArrayList<>();
        for (Video video : pageResult.getItems()) {
            VideoVo vo = new VideoVo();

            //封装视频发布者的信息
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());

            //封装视频信息
            vo.setId(video.getId().toHexString());
            vo.setCover(video.getPicUrl());
            vo.setVideoUrl(video.getVideoUrl());
            vo.setSignature(video.getText());

            vo.setLikeCount(0);
            vo.setCommentCount(0);

            voList.add(vo);
        }

        PageResult<VideoVo> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity passPublish(List<String> item) {
        if (!CollectionUtils.isEmpty(item) && item.size() > 0) {
            for (String pid : item) {
                Publish publish = publishApi.findById(pid);
                publish.setState(1);
                publishApi.updateState(publish);
            }
            return ResponseEntity.ok(MESSAGE);
        }
        return ResponseEntity.badRequest().body("BadRequest");
    }

    public ResponseEntity rejectPublish(List<String> item) {
        if (!CollectionUtils.isEmpty(item) && item.size() > 0) {
            for (String pid : item) {
                // 通过pid 查找publish
                Publish publish = publishApi.findById(pid);
                // 删除动态
                publishApi.removePublishByPid(pid);
                // 删除相册
                publishApi.removeAlbumPublish(publish.getUserId(), pid);
                // 删除好友的时间线
                List<Friend> friends = friendApi.findFriendListByUserId(publish.getUserId());
                for (Friend friend : friends) {
                    friendApi.removeTimeLine(friend.getFriendId(), publish.getUserId());
                }
            }
            return ResponseEntity.ok(MESSAGE);
        }
        return ResponseEntity.badRequest().body("BadRequest");
    }
}
